package com.weizhu.swufer.core.loadbalance;

import com.weizhu.swufer.core.entity.RpcBaseInfo;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class RandomLoadBalancer extends AbstractLoadBalancer{


    @Override
    public String doSelect(String serviceKey,List<RpcBaseInfo> rpcList,long listHashCode) {
        int size = rpcList.size();
        int totalWeight = 0;
        int[] weights = new int[size];
        int maxWeight = 0;
        int minWeight = Integer.MAX_VALUE;
        for (int i = 0; i < size; i++) {
            int iWeight = Math.max(0, rpcList.get(i).getWeight());
            totalWeight += iWeight;
            weights[i] = totalWeight;
            if (iWeight > maxWeight){
                maxWeight = iWeight;
            }
            if (iWeight < minWeight){
                minWeight = iWeight;
            }
        }
        if (maxWeight == minWeight){
            return rpcList.get(ThreadLocalRandom.current().nextInt(size)).getAddress();
        }

        int random = ThreadLocalRandom.current().nextInt(totalWeight);
        for (int i = 0; i < size; i++) {
            if (weights[i] > random){
                return rpcList.get(i).getAddress();
            }
        }
        return null;
    }

}
